package top.scsoul.boot.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.scsoul.boot.entity.SysUser;
import top.scsoul.boot.dao.SysUserDao;
import top.scsoul.boot.service.SysUserService;
import org.springframework.stereotype.Service;
import top.scsoul.boot.utils.Md5Util;
import top.scsoul.boot.utils.ServletUtil;
import top.scsoul.boot.utils.StringUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

/**
 * (SysUser)表服务实现类
 *
 * @author 曹波涛
 * @since 2021-06-10
 */
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    @Override
    public SysUser queryById(Integer userId) {
        return sysUserDao.queryById(userId);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<SysUser> queryAllByLimit(int offset, int limit) {
        return sysUserDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @Override
    public SysUser insert(SysUser sysUser) {
        sysUserDao.insert(sysUser);
        return sysUser;
    }

    /**
     * 修改数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @Override
    public SysUser update(SysUser sysUser) {
        this.sysUserDao.update(sysUser);
        return this.queryById(sysUser.getUserId());
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer userId) {
        return sysUserDao.deleteById(userId) > 0;
    }

    @Override
    public boolean loginCheck(String usercode, String password) {
        SysUser sysUser = sysUserDao.queryByUserCode(usercode);
        boolean uerNotExists = ObjectUtils.isEmpty(sysUser);
        if (uerNotExists) {
            throw new RuntimeException("用户不存在");
        }
        String userPassword = sysUser.getUserPassword();
        boolean loginTest = Md5Util.test(userPassword, password);
        if (!loginTest) {
            throw new RuntimeException("密码错误");
        }
        //存Session
        HttpSession session = ServletUtil.getSession();
        session.setAttribute("user", sysUser);
        return true;
    }
}